package com.dianrui.moonfire.activity;

import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.adapter.DespoitCouponAdapter;
import com.dianrui.moonfire.alipay.PayResult;
import com.dianrui.moonfire.bean.Coupon;
import com.dianrui.moonfire.bean.DepositCoupon;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.util.NoDoubleClickUtils;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.dianrui.moonfire.view.HorizontalListViewNew;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
/**
 * Description:缴纳押金
 * User: luoziyin
 * Date: 2020-8-17
 */
public class DepositActivity extends BaseActivity {
    private List<DepositCoupon> mcouponList = new ArrayList<>();
    private DespoitCouponAdapter couponAdapter;
    private String currentMoney, couponId;
    private String settingId;
    private String isDepositAuth;
    private String vehicleAreaIds;
    private String settingIds;
    private String isborrowCar;


    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.listview)
    ListView listView;

    @BindView(R.id.emptyView)
    LinearLayout emptyView;



    @Override
    public int getContentViewId() {
        return R.layout.activity_despoit;
    }

    @Override
    public void initView() {
        customInit(true);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                settingId = bundle.getString("setting_id");
                isDepositAuth = bundle.getString("isDespoitBack");
                vehicleAreaIds = bundle.getString("vehicle_area_id");
                isborrowCar = bundle.getString("isborrowCar");
            }

        }
        title.setText(getString(R.string.deponsit_titles));
        getCoupon();
        couponAdapter = new DespoitCouponAdapter(DepositActivity.this, mcouponList);
        listView.setAdapter(couponAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
                if (mcouponList != null && mcouponList.size() > 0) {
                    DepositCoupon depositCoupon = mcouponList.get(position);
                    if (depositCoupon != null) {
                        String sellPrice=depositCoupon.sell_price;
                        String type=depositCoupon.type;
                        String ids=depositCoupon.ids;
                        if (type.equals("1")) {
                            type="2";
                        }else {
                            type="5";
                        }
                        createPayDialog(sellPrice,type,ids);
                    }
                }

            }
        });
    }

    @Override
    public void initData() {
    }



    private void getCoupon() {
        if (mcouponList != null && mcouponList.size() > 0) {
            mcouponList.clear();
        }
        XHttpRequest.getInstance().postRequests(Url.COUPON, "", new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {

                                String data= JsonUtils.getJsonStr(result,"data");
                                if (!StringUtils.isEmpty(data)) {
                                    List<DepositCoupon> list= JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<DepositCoupon>>(){}.getType());
                                    if (list != null && list.size()>0) {
                                        mcouponList.addAll(list);
                                        if (couponAdapter != null) {
                                            couponAdapter.refresh(mcouponList);
                                        }
                                        listView.setVisibility(View.VISIBLE);
                                    }else {
                                        listView.setVisibility(View.GONE);
                                    }
                                }
                            } else {
                                listView.setVisibility(View.GONE);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (mcouponList.size() <= 0) {
                        listView.setVisibility(View.GONE);
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        listView.setVisibility(View.VISIBLE);
                        emptyView.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @OnClick({R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if ("1".equals(isDepositAuth)) {//1是正常finish
                    finish();
                } else {//反之跳主页
                    JumpActivitys(MainActivity.class);
                    finish();
                }
                break;

            default:
                break;
        }
    }

    private void createPayDialog(final String money,final String type, final String ids) {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(DepositActivity.this);
        View view = LayoutInflater.from(DepositActivity.this).inflate(R.layout.dialog_pays, null);
        Button pay = view.findViewById(R.id.pay);
        ImageView close = view.findViewById(R.id.close);
        RelativeLayout clickZfb = view.findViewById(R.id.click_zfb);
        RelativeLayout clickWx = view.findViewById(R.id.click_wx);
        final TextView showMoney = view.findViewById(R.id.show_dialog_money);
        final CheckBox cbZfb = view.findViewById(R.id.cb_zfb);
        final CheckBox cbWx = view.findViewById(R.id.cb_wx);

        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(MyUtil.formatBy2Float(Float.parseFloat(money),2));
        showMoney.setText(stringBuilder.toString());

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog.dismiss();
            }
        });
        clickZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(true);
                cbWx.setChecked(false);
            }
        });
        clickWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
            }
        });
        cbZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(true);
                cbWx.setChecked(false);
            }
        });
        cbWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
            }
        });
        pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cbWx.isChecked()) {
                    bottomSheetDialog.dismiss();
                    wxPays(showMoney.getText().toString(), type,ids);
                } else if (cbZfb.isChecked()) {
                    bottomSheetDialog.dismiss();
                    alipays(showMoney.getText().toString(), type,ids);
                }
            }
        });
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCanceledOnTouchOutside(false);
        bottomSheetDialog.show();
    }

    private void wxPays(String money,String type,String ids) {
        showLoadingDialog("请稍候...");
        JsonObject payWx = new JsonObject();
        payWx.addProperty("type", type);
        payWx.addProperty("payment_mode", "2");
        payWx.addProperty("money", money);
        payWx.addProperty("ids", ids);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            payWx.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
            payWx.addProperty("area_id", SPUtils.getInstance().getString("area_id"));
        }
        XHttpRequest.getInstance().postRequests(Url.PAY, payWx.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                IWXAPI api = WXAPIFactory.createWXAPI(DepositActivity.this, Constant.WXAppID, true);
                                if (!api.isWXAppInstalled()) {
                                    ToastUtil.showToast("没有安装微信客户端");
                                }
                                PayReq payReq = new PayReq();

                                payReq.appId = jsonObject.optJSONObject("data").optString("appid");
                                payReq.partnerId = jsonObject.optJSONObject("data").optString("partnerid");
                                payReq.prepayId = jsonObject.optJSONObject("data").optString("prepayid");
                                payReq.packageValue = jsonObject.optJSONObject("data").optString("package");
                                payReq.nonceStr = jsonObject.optJSONObject("data").optString("noncestr");
                                payReq.timeStamp = jsonObject.optJSONObject("data").optString("timestamp");
                                payReq.extData = "DepositPay";
                                payReq.sign = jsonObject.optJSONObject("data").optString("sign");
                                api.sendReq(payReq);
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void alipays(String money,String type,String ids) {
        showLoadingDialog("请稍候...");
        JsonObject payZfb = new JsonObject();
        payZfb.addProperty("type", type);
        payZfb.addProperty("payment_mode", "3");
        payZfb.addProperty("money", money);
        payZfb.addProperty("ids", ids);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            payZfb.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
            payZfb.addProperty("area_id", SPUtils.getInstance().getString("area_id"));
        }

        XHttpRequest.getInstance().postRequests(Url.PAY, payZfb.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                if (!MyUtil.checkAliPayInstalled(DepositActivity.this)) {
                                    ToastUtil.showToast(getString(R.string.zfb_installed));
                                    return;
                                }
                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            PayTask alipay = new PayTask(DepositActivity.this);
                                            final Map<String, String> res = alipay.payV2(jsonObject.getJSONObject("data").optString("contents"), true);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    PayResult payResult = new PayResult(res);
                                                    String resultStatus = payResult.getResultStatus();
                                                    if ("9000".equals(resultStatus)) {
                                                        EventBus.getDefault().post(EventBusConstants.REFRESH_WALLET_LIST);
                                                        ToastUtil.showToast(getString(R.string.pay_success));
                                                        if (isborrowCar.equals("1")) {
                                                            finish();
                                                        } else {
                                                            JumpKillActivitys(MainActivity.class);
                                                        }

                                                    } else {
                                                        ToastUtil.showToast(getString(R.string.pay_failed));
                                                    }
                                                }
                                            });
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                };

                                Thread payThread = new Thread(payRunnable);
                                payThread.start();

                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ("1".equals(isDepositAuth)) {
                finish();
            } else {
                JumpActivitys(MainActivity.class);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
